package com.fau.template.controller;

import java.io.File;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.fau.template.service.BaseAllService;
import com.fau.template.util.Page;
import com.fau.template.util.SystemConfig;

@Component
public abstract class SpringController {
	
	private static final Logger log = Logger.getLogger(SpringController.class);
	
	@Resource
	private BaseAllService baseAllService;
	protected Page pageBean;
	protected Map<String, Object> map;
	protected List<?> list;
	
	protected BaseAllService getBaseAllService() {
		return baseAllService;
	}
	
	/**
	 * @desc 上传文件
	 * @author liy
	 * @throws Exception 
	 * @datetime 2015年1月15日,下午7:21:30
	 */
	protected String uploadFile(HttpServletRequest request, MultipartFile file) throws Exception {
		String ct = file.getContentType();
		
		if(SystemConfig.BMP_TYPE.equals(ct) || SystemConfig.JPEG_TYPE.equals(ct)
				|| SystemConfig.PNG_TYPE.equals(ct) || SystemConfig.GIF_TYPE.equals(ct)) {
		} else {
			log.error("图片类型不正确！");
			throw new Exception("图片类型不正确！");
		}
		
		if(file.getSize() > SystemConfig.IMG_SIZE) {
			log.error("");
			throw new Exception("图片过大！");
		}
		
		StringBuilder savePath = new StringBuilder(request.getServletContext().getRealPath("statics/upload"));
		File uploadDir = new File(savePath.toString());
		if(!uploadDir.canWrite()){
			log.error("文件目录是只读的或不存在");
			throw new Exception("文件目录是只读的或不存在");
		}
		
		Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH) + 1;
		
		savePath.append(File.separator).append(year).append(File.separator);
		savePath.append(month).append(File.separator);
		
		// 每年每个月会创建一个文件夹
		File dirFile = new File(savePath.toString());
		if(!dirFile.exists()){
			//noinspection ResultOfMethodCallIgnored
			dirFile.mkdirs();
		}
		String fileName = file.getOriginalFilename();
		String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();	// 后缀名
		String newFileName = c.getTimeInMillis() + "" + RandomUtils.nextInt(1000, 10000);
		
		File newFile = new File(savePath.append(newFileName).append(".").append(fileExt).toString());
		file.transferTo(newFile);
		
		String saveURL = request.getContextPath()+ File.separator + "statics" + File.separator + "upload" + File.separator + year + File.separator + month + File.separator
				+ newFile.getName();
		return saveURL;
	}
}
